package pay

import (
	"context"
	"fmt"
	"go-demo/designpattern/adapter/pay/sdk"
)

// 支付宝支付代理
type AlipayAdapter struct {
	client *sdk.AlipayClient
}

// NewAlipayAdapter 创建支付宝支付代理
func NewAlipayAdapter(appId, appSecret string) *AlipayAdapter {
	return &AlipayAdapter{
		client: &sdk.AlipayClient{
			AppID:     appId,
			AppSecret: appSecret,
		},
	}
}

// Name 支付网关名称
func (a *AlipayAdapter) Name() string {
	return "alipay"
}

// Pay 支付
func (a *AlipayAdapter) Pay(ctx context.Context, request *PaymentRequest) (*PaymentResponse, error) {
	// 转换请求参数
	req := sdk.AlipayRequest{
		OutTradeNo:  request.OrderID,
		TotalFee:    request.Amount,
		Subject:     request.Description,
		Body:        fmt.Sprintf("Customer: %s", request.CustomerID),
		PaymentType: 1,
	}
	// 调用支付宝接口
	resp, err := a.client.ProcessAlipayPayment(req)
	if err != nil {
		return nil, err
	}
	// 转换响应参数
	success := resp.IsSuccess == "T"
	response := &PaymentResponse{
		Success:    success,
		PaymentID:  resp.TradeNo,
		StatusCode: resp.ResultCode,
		Message:    resp.Error,
	}
	return response, nil
}
